package com.block.job.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.service.LogFactory;
import com.block.db.entity.SourceDataCountInfo;
import com.block.db.mapper.SourceDataCountInfoMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Set;

@Component
public class UpdateSourceCheckNumberJob {

    private static final Logger log = LogFactory.getJobLog();
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    SourceDataCountInfoMapper sourceDataCountInfoMapper;
    @Autowired
    TransactionTemplate transactionTemplate;

    /**
     * 更新 线索撞库数据
     * @throws Exception
     */
    @XxlJob("updateSourceCheckNumberJob")
    public void delete() throws Exception {
        XxlJobHelper.log("更新 线索撞库数据---------开始执行--------");

        String dateInfo = LocalDate.now().toString();
        String redisKey = StrUtil.format(RedisKeyConstant.SOURCE_CHECK_NUMBER_CHANNEL, dateInfo, "*");

        Set<String> keys = stringRedisTemplate.keys(redisKey);
        for (String key : keys) {
            String[] split = key.split("::");
            String channelCode = split[split.length - 1];
            String checkNumber = stringRedisTemplate.opsForValue().get(key);

            if (ObjectUtil.isNotEmpty(checkNumber)){
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {

                        SourceDataCountInfo dataCountInfo = sourceDataCountInfoMapper.selectByDateInfoAndChannelCode(channelCode, dateInfo);

                        SourceDataCountInfo updateEntity = new SourceDataCountInfo();
                        updateEntity.setCheckNumber(Integer.valueOf(checkNumber));

                        if (ObjectUtil.isNotEmpty(dataCountInfo)){
                            updateEntity.setId(dataCountInfo.getId());
                            sourceDataCountInfoMapper.updateById(updateEntity);
                        }
                        return null;
                    }
                });
            }
        }

        XxlJobHelper.log("更新 线索撞库数据---------结束执行--------");
    }

}
